﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

namespace Jy123.Web.Vote
{
    public partial class VoteJoin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int userID;//用户ID
            string strUserIdFromCookie = Common.Cookie.getCookie("UserID");
            if (string.IsNullOrEmpty(strUserIdFromCookie))
            {
                Response.Redirect("/");
            }
            userID = int.Parse(strUserIdFromCookie);

            int voteID = Convert.ToInt32(Request.QueryString["voteID"]);

            string strhidVoteID =Request.Form["hidVoteID"];
            if (!(voteID > 0))
            {
                if(!string.IsNullOrEmpty(strhidVoteID))
                {
                    voteID = Convert.ToInt32(strhidVoteID);
                }                  
            }

            string msg = string.Empty;

            string strAlterComm = Request.Form["alterComm"];
            if (strAlterComm == "修改")
            {
                string strtxtComment = Request.Form["txtComment"];
                new Jy123.BLL.User.Vote().UpdateToVoteCommentContent(userID, voteID, strtxtComment);
            }

            string strSubmit = Request.Form["submit"];
            if (strSubmit == "我要投票")
            {
                string strVoteID = Request.Form["hidVoteID"];
                voteID = Convert.ToInt32(strVoteID);
               msg = ToVote(strSubmit,userID, voteID,msg);//进行投票 
            }
            string type = Request.QueryString["Type"];
            //if (type == "del")
            //{
            //    string commentID = Request.QueryString["id"];
            //    new BLL.User_VoteComm().Delete(Convert.ToInt32(commentID));
            //}
            //公共部分
            #region 页面处理
            StringBuilder sbHtml = new StringBuilder(Cache["user_votejoin"].ToString());//主sb            
            sbHtml = sbHtml.Replace("$Header$", Cache["user_header"].ToString());//头部
            sbHtml = sbHtml.Replace("$Footer$", Cache["user_footer"].ToString());//底部
            sbHtml = sbHtml.Replace("$Navigation$", Cache["user_navigation_down"].ToString());//左侧导航
            sbHtml = sbHtml.Replace("$LeftUserFriendAdd$", Cache["user_friendadd"].ToString());//左侧快速添加好友
            sbHtml = sbVoteInfo(sbHtml, voteID);//投票信息
            sbHtml = sbHtml.Replace("$VoteOption$",VoteOption(voteID));//投票选项列表
            int blIsVoted = new Jy123.BLL.User.Vote().ToVoted(userID, voteID);
            if (blIsVoted == 0)
            {
                sbHtml = sbHtml.Replace("你已投过票了", "我要投票");
                sbHtml = sbHtml.Replace("input_btn_n", "input_btn");
                sbHtml = sbHtml.Replace("disabled='disabled'", "");
                sbHtml = sbHtml.Replace("$ToComment$", "<textarea name='CommentContent'>发表你的意见</textarea></li>");
            }
            else
            {
                sbHtml = sbHtml.Replace("$ToComment$", string.Empty);
            }
            sbHtml = sbHtml.Replace("$VotedUserList$",VotedUserList(userID,voteID));
            sbHtml = sbHtml.Replace("$VoteID$",voteID.ToString());

            Jy123.Model.User_Main mUser = new Jy123.Model.User_Main();
            mUser = new Jy123.BLL.User_Main().GetModel(userID);
            sbHtml = sbHtml.Replace("$UserName$",mUser.UserName);

            //判断用户是否有头像
            mUser.Portrait = new Jy123.BLL.User.SPace().DefaultPortrait(userID);

            sbHtml = sbHtml.Replace("$Portrait$",mUser.Portrait);
            sbHtml = sbHtml.Replace("$UserID$",userID.ToString());

            sbHtml = sbHtml.Replace("$VoteCommentList$",VoteCommentList(userID,voteID));
            sbHtml = sbHtml.Replace("$所选投票项$",VotedOptionList_My(userID,voteID));
            #endregion
            
            sbHtml = sbHtml.Replace("$CommentContentMy$",new Jy123.BLL.User.Vote().ToVoteCommentContent(userID,voteID));
            Response.Write(sbHtml.ToString() + msg);//最终写出整个Html页面
        }
        /// <summary>
        /// 投票选项
        /// </summary>
        /// <param name="VoteID">投票ID</param>
        /// <returns>字符串</returns>
        private string VoteOption(int VoteID)
        {
            Jy123.Model.User_Vote mVote = new Jy123.Model.User_Vote();
            mVote = new Jy123.BLL.User_Vote().GetModel(VoteID);
            int voteMode = (int)mVote.Mode;//投票类型

            StringBuilder sbList = new StringBuilder();
            string strHtml = Cache["user_votejoin_option"].ToString();
            DataTable dtVoteOption = new Jy123.BLL.User.Vote().VoteOptionList(VoteID, 1, int.MaxValue, "*", "").Tables[0];
            for (int i = 0; i < dtVoteOption.Rows.Count; i++)
            {
                string strRow = strHtml;
                strRow = strRow.Replace("$VoteOptionName$",dtVoteOption.Rows[i]["OptionName"].ToString());
                strRow = strRow.Replace("$VoteOptionCount$", dtVoteOption.Rows[i]["Count"].ToString());
                strRow = strRow.Replace("$Red$",new Jy123.Common.Rand().Random(1,255).ToString());
                //strRow = strRow.Replace("$Green$", Jy123.Common.Rand.Bytes(1, true)[0].ToString());
                //strRow = strRow.Replace("$Blue$", Jy123.Common.Rand.Bytes(1, true)[0].ToString());
                strRow = strRow.Replace("$Green$",new Jy123.Common.Rand().Random(1, 255).ToString());
                strRow = strRow.Replace("$Blue$",new Jy123.Common.Rand().Random(1, 255).ToString());

                strRow = strRow.Replace("$OptionID$",dtVoteOption.Rows[i]["ID"].ToString());
                if (voteMode == 0)//如果为复选
                { 
                    strRow =strRow.Replace("type='radio' name='rad'","type='checkbox' name='chk'");
                }
                int VoteCount = new Jy123.BLL.User.Vote().VoteRecordCount(VoteID);
                double percent = 0;
                if (VoteCount > 0)
                { 
                    percent = Convert.ToDouble(dtVoteOption.Rows[i]["Count"]) / Convert.ToDouble(VoteCount)*100;
                    //strRow = strRow.Replace("$Percent$", percent.ToString().Substring(0, 5));
                    //strRow = strRow.Replace("$Percent*3$", (percent * 3).ToString().Substring(0, 5));
                }
                
                strRow = strRow.Replace("$Percent$", percent.ToString("0.00"));
                strRow = strRow.Replace("$Percent*3$", (percent * 3).ToString("0.00"));

                sbList.Append(strRow);
            }
            
            return sbList.ToString();
        }        
        /// <summary>
        /// 投票信息
        /// </summary>
        /// <param name="sbHtml">sb</param>
        /// <param name="voteID">投票的ID</param>
        /// <returns>字符串</returns>
        private StringBuilder sbVoteInfo(StringBuilder sbHtml,int voteID)
        {
            Jy123.Model.User_Vote mVote = new Jy123.Model.User_Vote();
            mVote = new Jy123.BLL.User_Vote().GetModel(voteID);
            sbHtml = sbHtml.Replace("$AddTime$", mVote.AddTime.ToString());
            sbHtml = sbHtml.Replace("$JoinCount$", mVote.JoinCount.ToString());
            sbHtml = sbHtml.Replace("$VoteTitle$", mVote.Title);
            return sbHtml;
        }
        /// <summary>
        /// 进行投票
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="voteID">投票的ID</param>
        /// <param name="msg">消息</param>
        private string ToVote(string strSubmit,int userID,int voteID,string msg)
        {            
                int blIsVoted = new Jy123.BLL.User.Vote().ToVoted(userID, voteID);
                if (blIsVoted>0)
                {
                    //加入动态
                    Jy123.Model.User_Main mUserForState = new Jy123.Model.User_Main();
                    Jy123.Model.User_Main mUserFrd = new Jy123.Model.User_Main();
                    Jy123.BLL.User_Main bllUserForState = new Jy123.BLL.User_Main();
                    Jy123.Model.User_Vote mVote = new Jy123.BLL.User_Vote().GetModel(voteID);
                    mUserFrd = bllUserForState.GetModel(Convert.ToInt32(mVote.FUser));
                    new Jy123.BLL.Public.State().CreateVoteState(mUserForState,mUserFrd,mVote, (int)Jy123.BLL.Public.EnumConfig.StateActionType.CreateVote);
                    //加入动态
                    msg = "<script>$(function(){$.moonbox.warning('已投过票!');})</script>";
                }
                else
                {
                    string strRadio = Request.Form["rad"];
                    string chk = Request.Form["chk"];
                    string strOption = string.Empty;
                    if (!string.IsNullOrEmpty(strRadio))
                    {
                        strOption = strRadio;
                        //投票记录表
                        VoteRadio(userID, voteID,strOption,msg);
                    }
                    else if (!string.IsNullOrEmpty(chk))
                    {
                        strOption = chk;
                        VoteChk(userID, voteID, strOption, msg);
                    }
                    else
                    {
                        msg = "<script>$(function(){$.moonbox.warning('请选择投票项!');})</script>";
                    }
                    
                }
                return msg;
        }
        private string VoteRadio(int userID, int voteID,string strOption,string msg)
        {
            Jy123.Model.User_ToVote mToVote = new Jy123.Model.User_ToVote();
            Jy123.BLL.User_ToVote bllToVote = new Jy123.BLL.User_ToVote();
            mToVote.FUser = userID;
            mToVote.FVote = voteID;
            mToVote.FOption = strOption;
            mToVote.CommentContent = Request.Form["CommentContent"];
            bllToVote.Add(mToVote);
            //投票主表
            Jy123.Model.User_Vote mVote = new Jy123.Model.User_Vote();
            Jy123.BLL.User_Vote bllVote = new Jy123.BLL.User_Vote();
            mVote = bllVote.GetModel(voteID);
            mVote.JoinCount = mVote.JoinCount + 1;
            bllVote.Update(mVote);
            //投票选项表更新
            Jy123.Model.User_VoteOption mVoteOption = new Jy123.Model.User_VoteOption();
            Jy123.BLL.User_VoteOption bllVoteOption = new Jy123.BLL.User_VoteOption();
            mVoteOption = bllVoteOption.GetModel(Convert.ToInt32(strOption));
            mVoteOption.Count = mVoteOption.Count + 1;
            bllVoteOption.Update(mVoteOption);
            msg = "<script>$(function(){$.moonbox.ok('投票成功!!');})</script>";
            return msg;
        }
        private string VoteChk(int userID, int voteID, string strOption, string msg)
        {
            string[] arrayOption = strOption.Split(',');
            for (int i = 0; i < arrayOption.Length; i++)
            {
                Jy123.Model.User_ToVote mToVote = new Jy123.Model.User_ToVote();
                Jy123.BLL.User_ToVote bllToVote = new Jy123.BLL.User_ToVote();
                mToVote.FUser = userID;
                mToVote.FVote = voteID;
                mToVote.FOption = arrayOption[i];
                mToVote.CommentContent = Request.Form["CommentContent"];
                bllToVote.Add(mToVote);                
                //投票选项表更新
                Jy123.Model.User_VoteOption mVoteOption = new Jy123.Model.User_VoteOption();
                Jy123.BLL.User_VoteOption bllVoteOption = new Jy123.BLL.User_VoteOption();
                mVoteOption = bllVoteOption.GetModel(Convert.ToInt32(arrayOption[i]));
                mVoteOption.Count = mVoteOption.Count + 1;
                bllVoteOption.Update(mVoteOption);                
            }
            //投票主表
            Jy123.Model.User_Vote mVote = new Jy123.Model.User_Vote();
            Jy123.BLL.User_Vote bllVote = new Jy123.BLL.User_Vote();
            mVote = bllVote.GetModel(voteID);
            mVote.JoinCount = mVote.JoinCount + 1;
            bllVote.Update(mVote);
            msg = "<script>$(function(){$.moonbox.ok('投票成功!!');})</script>";
            return msg;
        }
        /// <summary>
        /// 用户已投过票的选项列表
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="voteID">投票ID</param>
        /// <returns>字符串</returns>
        private string VotedOptionList(int userID, int voteID)
        {
            StringBuilder sbHtml = new StringBuilder();
            string strHtml = "投票项<br />";
            DataTable dtVotedOptionList = new Jy123.BLL.User.Vote().VotedOptionList(userID, voteID, 1, int.MaxValue, "*", "ID").Tables[0];
            for (int i = 0; i < dtVotedOptionList.Rows.Count; i++)
            {
                string str = strHtml;
                if (dtVotedOptionList.Rows.Count > 1)
                {str = str.Replace("投票项", dtVotedOptionList.Rows[i]["OptionName"].ToString());}
                else
                { str = str.Replace("投票项<br />", dtVotedOptionList.Rows[i]["OptionName"].ToString()); }
                sbHtml.Append(str);
            }
            return sbHtml.ToString();
        }
        /// <summary>
        /// 当前用户已投过票的选项列表
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="voteID">投票ID</param>
        /// <returns>字符串</returns>
        private string VotedOptionList_My(int userID, int voteID)
        {
            StringBuilder sbHtml = new StringBuilder();
            string strHtml = "$所选投票项$";
            DataTable dtVotedOptionList = new Jy123.BLL.User.Vote().VotedOptionList(userID, voteID, 1, int.MaxValue, "*", "ID").Tables[0];
            for (int i = 0; i < dtVotedOptionList.Rows.Count; i++)
            {
                string str = strHtml;
                //if (dtVotedOptionList.Rows.Count > 1)
                //{ str = str.Replace("$所选投票项$", dtVotedOptionList.Rows[i]["OptionName"].ToString()+"<br />"); }
                //else
                //{ str = str.Replace("$所选投票项$", dtVotedOptionList.Rows[i]["OptionName"].ToString()); }
                str = str.Replace("$所选投票项$", dtVotedOptionList.Rows[i]["OptionName"].ToString());
                sbHtml.Append(str);
            }
            return sbHtml.ToString();
        }
        /// <summary>
        /// 已投票的用户列表
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>字符串</returns>
        private string VotedUserList(int userID,int voteID)
        {
            StringBuilder sbHtml = new StringBuilder();
            string strHtml = Cache["user_voteduserlist"].ToString();
            DataTable dtVotedUserList = new Jy123.BLL.User.Vote().VotedUserList(userID, voteID, 1, int.MaxValue, "*", "FUser IN (SELECT FFriend FROM User_Friend WHERE FUser = '" + userID + "')", "fuser asc").Tables[0];
            for (int i = 0; i < dtVotedUserList.Rows.Count; i++)
            {
                string str = strHtml;
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtVotedUserList.Rows[i]["FUser"]));

                str = str.Replace("$UserID$",dtVotedUserList.Rows[i]["FUser"].ToString());
                str = str.Replace("$UserName$", dtVotedUserList.Rows[i]["UserName"].ToString());
                str = str.Replace("$Portrait$", userPortrait);
                str = str.Replace("$VotedOptionList$", VotedOptionList(Convert.ToInt32(dtVotedUserList.Rows[i]["FUser"]),voteID));
                str = str.Replace("$CommentContent$",dtVotedUserList.Rows[i]["CommentContent"].ToString());
                sbHtml.Append(str);
            }
            return sbHtml.ToString();
        }
        /// <summary>
        /// 投票评论列表
        /// </summary>
        /// <param name="voteID">投票ID</param>
        /// <returns>字符串</returns>
        private string VoteCommentList(int userID,int voteID)
        {
            StringBuilder sbHtml = new StringBuilder();
            string strHtml = Cache["user_votecomment_row"].ToString();
            DataTable dtVoteComment = new Jy123.BLL.User.Vote().VoteCommentList(voteID, 1, int.MaxValue, "*", "Fvote='" + voteID + "'", "AddTime ASC").Tables[0];
            string strDel = @"<a href=""javascript:myAjax('/Vote/VoteCommentDel.ashx','CommentID='+$CommentID$);"" class=""imgdel"" ><img src=""/images/del_blog.gif"" alt=""删除"" /></a>";
            for (int i = 0; i < dtVoteComment.Rows.Count; i++)
            {
                string str = strHtml;
                if (dtVoteComment.Rows[i]["FUser"].ToString().Equals(userID.ToString()))
                {
                    str = str.Replace("$imgdel$", strDel);
                }
                else
                { str = str.Replace("$imgdel$", ""); }
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtVoteComment.Rows[i]["FUser"]));

                str = str.Replace("$AddTime$",dtVoteComment.Rows[i]["AddTime"].ToString());
                str = str.Replace("$UserName$", dtVoteComment.Rows[i]["UserName"].ToString());
                str = str.Replace("$UserID$", dtVoteComment.Rows[i]["FUser"].ToString());
                str = str.Replace("$Portrait$", userPortrait);
                str = str.Replace("$CommentContent$", dtVoteComment.Rows[i]["CommentContent"].ToString());
                str = str.Replace("$CommentID$",dtVoteComment.Rows[i]["ID"].ToString());
                
                sbHtml.Append(str);
            }
            return sbHtml.ToString();
        }
        
    }
}
